/**
 * @param {number[]} data
 * @return {boolean}
 */
 var validUtf8 = function(data) {
  let cnt = 0;
  const ind = 0b01111111;
  const pt1 = 0b10000000;
  const pt2 = 0b01000000;
  const countOnes = n => {
      let digit = 0b10000000;
      let cnt = 0;
      while((n & digit) !== 0) {
          cnt ++;
          digit >>= 1;
      }
      return cnt;
  }
  // console.log(countOnes(250));
  for(d of data) {
      if(cnt > 0){
          if(!((d & pt1) === pt1 && (d & pt2) === 0)) {
              return false;
          }
          cnt --;
      } else {
          let c = countOnes(d);
          if(c === 0) {
              continue
          } else if(c === 1 || c > 4) {
              return false;
          } else {
              cnt = c - 1;
          }
      } 
  }
  return cnt === 0
};